import axios, { type InternalAxiosRequestConfig, type AxiosError, type AxiosRequestConfig } from "axios"



interface AxiosRequestConfigEx extends AxiosRequestConfig {
    donNotShowLoading?: boolean
}



export type ResType<T = any> = {
    code: string;
    data: T;
    msg: string;
}

export type PageDataType<T> = {
    list: T[];
    pageNum: number;
    pageSize: number;
    total: number;
}

export type RolesType = {
    code: string;
    createTime?: string;
    id?: number;
    name: string;
    sort: number;
    status: number;
}


const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_PATH,
    timeout: 2000
})


export const service = <T = any>(config: AxiosRequestConfigEx) => {
    return instance.request<ResType<T>>(config)
        .then(response => { return response.data })
}


// http request 拦截器
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {

    // 使用 set 方法来设置 headers  
    config.headers.set('Content-Type', 'application/json');
    // return {
    //   ...config,
    //   headers: {
    //     'x-access-token': '', // 请求头中携带token信息
    //   }
    // }

    return config
},
    (error: AxiosError) => {
        // 请求报错
        Promise.reject(error)
    })


instance.interceptors.response.use(
    response => {
        // 响应成功时做一些处理
        console.log('响应拦截器: ', response);
        return response;
    },
    error => {
        // 统一处理错误信息
        if (error.response.status === 401) {
            // 如果是 401 错误，可能是未授权，跳转到登录页面
            window.location.href = '/login';
        } else if (error.response.status === 500) {
            // 服务器错误
            console.error('服务器错误');
        }

        return Promise.reject(error);
    }
);


export const requestGetRolesPage = () => {
    return service<PageDataType<RolesType>>({
        method: 'get',
        url: '/roles/page',
        params: { pageNum: 1, pageSize: 50 },
    })
}
export const userdengru = (data: any) => {
    return service({
        method: 'post',
        url: '/auth/login',
        data,
    })
}

export const addRole = (data: any) => {
    return service({
        method: 'post',
        url: '/roles',
        data,
    })
}
export const editRole = (roleId: string, data: RolesType) => {
    service({
        method: 'put',
        url: `/roles/${roleId}`,
        data
    })
}


export const delRole = (ids: string) => {

    instance.request({
        method: 'delete',
        url: `/roles/${ids}`,
    })
        .then(response => console.log('Deleted:', response.data))
        .catch(error => console.error(error));

}